package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.RegExp;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.DCity;
import cn.jekun.component.core.bean.gen.DProvince;
import cn.jekun.component.core.bean.gen.DRegion;
import cn.jekun.component.core.bean.gen.ErpDeliveryAddress;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.ErpDeliveryAddressService;
import cn.jekun.component.core.service.gen.ErpMerchandiseService;
/**
 * 
 * @author twj
 *
 */
@Service(AddressService.BEAN_NAME)
public class AddressService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.AddressService";
	@Override
	public String getNamespace() {
		return "ERP_DELIVERY_ADDRESS";
	}
	
	@Resource(name=ErpDeliveryAddressService.BEAN_NAME)
	ErpDeliveryAddressService erpDeliveryAddressService;
	
	
	/**
	 * 
	 * @param userId 用户代码
	 * @param provinceId 省份代码
	 * @param cityId 城市代码
	 * @param regionId 区域代码
	 * @param street 街道
	 * @param shipName 收货人姓名
	 * @param shipZip 邮编
	 * @param shipTel 电话号码
	 * @param mobile 手机号码
	 * @param def 默认 （0为非默认，1为默认）
	 * @param memo 备注
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject save(
			@RsUser.AnnoUserId
			String userId,
			//@RegExp(regExp="^[0-9]{6}$",message="省份编码为6位数字")
			@DProvince.AnnoProvinceId
			String provinceId,
			//@RegExp(regExp="^[0-9]{6}$",message="城市编码为6位数字")
			@DCity.AnnoCityId
			String cityId,
			//@RegExp(regExp="^[0-9]{6}$",message="区域编码为6位数字")
			@DRegion.AnnoRegionId
			String regionId,
			@ErpDeliveryAddress.AnnoStreet
			String street,
			@ErpDeliveryAddress.AnnoShipName
			String shipName,
			@RegExp(regExp="^[0-9]{6}$",message="邮编为6位数字")
			String shipZip,
			@Security
			String shipTel,
			@Mobile(message="手机号非法")
			String mobile,
			@ErpDeliveryAddress.AnnoDef
			String def,
			@ErpDeliveryAddress.AnnoMemo
			String memo,
			@Security
			String lng,
			@Security
			String lat){
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(provinceId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"省份编码不能为空");
		}
		if (StringUtils.isBlank(cityId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"城市编码不能为空");
		}
		if (StringUtils.isBlank(regionId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地区编码不能为空");
		}
		if (StringUtils.isBlank(street)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"街道地址不能为空");
		}
//		if (StringUtils.isBlank(shipZip)) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"邮编不能为空");
//		}
		
		if (StringUtils.isBlank(shipName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"收货人姓名不能为空");
		}
		
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号不能为空");
		}
		if (StringUtils.isBlank(def)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"默认值字段不能为空");
		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"备注不能为空");
		}
		if(StringUtils.isNotBlank(lng)){
			address.setLongitude(Double.parseDouble(lng));
		}
		if(StringUtils.isNotBlank(lat)){
			address.setLatitude(Double.parseDouble(lat));
		}
		Map totalMap = new HashMap();
		totalMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
		totalMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");
		SqlUtis.prepareSql(totalMap, "", SqlUtis.getSQL(totalMap, "a."
				+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQLRequired(totalMap, "a."
						+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ));
		List list = this.list(totalMap);
		if(list.size()>=5){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"不能超过5条收货地址");
		}
		//如果添加地址为默认地址则需要更新该用户对应的其他所有地址设置为非默认
		if(def.equals("1")){
			Map tempAddressMap = new HashMap();
			tempAddressMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
					+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpDeliveryAddress> tempList = this.list(tempAddressMap);
			if(tempList!=null){
				ErpDeliveryAddress tempAddress = new ErpDeliveryAddress();
				tempAddress.setDef("0");
				tempAddressMap.put("erpDeliveryAddress", tempAddress);
				SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempAddressMap);
			}
		}
		
		address.setAvailable("1");
		address.setUserId(userId);
		address.setProvinceId(provinceId);
		address.setCityId(cityId);
		address.setRegionId(regionId);
		address.setStreet(street);
		address.setShipName(shipName);
		address.setShipZip(shipZip);
		address.setShipTel(shipTel);
		address.setShipMobile(mobile);
		address.setDef(def);
		address.setMemo(memo);
		formMap.put("erpDeliveryAddress", address);
		String returnId = this.insert(formMap).toString();
		if(returnId==null){
			return executeRerutnFail(jsonObject);
		}else{
			jsonObject.put("addressId", returnId);
			jsonObject.put("shipMobile", mobile);
			jsonObject.put("shipName", shipName);
			jsonObject.put("memo", memo);
		return executeRerutn(jsonObject);
		}
	}
	/**
	 * 名为删除实则是update有效标志位为0
	 * @param addressId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject del(
			@RegExp(regExp="^[0-9]{0,50}$",message="地址编码非法")
			@ErpDeliveryAddress.AnnoAddressId
			String addressId){
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(addressId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址编码不能为空");
		}
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		address.setAvailable("0");
		formMap.put("erpDeliveryAddress", address);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		int total = this.update(formMap);//返回update的条数
		if(total == 0){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
	}
	/**
	 * 加载收货地址信息
	 * @param addressId 收货地址编码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject load(
			@RegExp(regExp="^[0-9]{0,50}$",message="地址编码非法")
			@ErpDeliveryAddress.AnnoAddressId
			String addressId){
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(addressId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址编码不能为空");
		}
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		ErpDeliveryAddress address = this.one(formMap);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONObject json =  JSONObject.fromObject(address, jsonConfig);
		String proviceName = "";
		String cityName = "";
		String regionName = "";
		if(address.getProvinceId()!=null){
			List<Map> tempList = this.listBySql("select province_name from D_PROVINCE a where a.province_id='"+address.getProvinceId()+"'");
			if(tempList != null && tempList.size()>0 ){
				proviceName = tempList.get(0).get("PROVINCE_NAME").toString();
			}
		}
		if(address.getCityId()!=null){
			List<Map> tempList = this.listBySql("select city_name from D_CITY a where a.city_id='"+address.getCityId()+"'");
			if(tempList != null && tempList.size()>0 ){
				cityName = tempList.get(0).get("CITY_NAME").toString();
			}
		}
		if(address.getRegionId()!=null){
			List<Map> tempList = this.listBySql("select region_name from D_REGION a where a.region_id='"+address.getRegionId()+"'");
			if(tempList != null && tempList.size()>0 ){
				regionName = tempList.get(0).get("REGION_NAME").toString();
			}
		}
		json.put("provinceName", proviceName);
		json.put("cityName", cityName);
		json.put("regionName", regionName);
		jsonObject.put("address", json);
		return executeRerutn(jsonObject);
	}
	/**
	 * 查询收货地址
	 * @param pageSize 页大小
	 * @param currentPage 当前页
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject query(
			@Security
			String pageSize,
			@Security
			String currentPage,
			@RegExp(regExp="^[0-9]{0,50}$",message="地址编码非法")
			@ErpDeliveryAddress.AnnoUserId
			String userId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		Map formMap = new HashMap();
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(currentPage)) {
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
		formMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");//查有效标识位
		formMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),SqlUtis.orderBy(" def desc nulls last"));
		JSONArray jsonArray = JSONArray.fromObject(this.list(formMap, page), jsonConfig);
		jsonObject.put("addressList", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		return executeRerutn(jsonObject);
	}
	/**
	 * 名为修改实则update有效标识为0另外添加一条新的数据
	 * @param addressId 收货地址编码
	 * @param userId 用户代码
	 * @param provinceId 省份代码
	 * @param cityId 城市代码
	 * @param regionId 区域代码
	 * @param street 街道
	 * @param shipName 收货人姓名
	 * @param shipZip 邮编
	 * @param shipTel 电话号码
	 * @param mobile 手机号码
	 * @param def 默认 （0为非默认，1为默认）
	 * @param memo 备注
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject update(
			@RegExp(regExp="^[0-9]{0,50}$",message="地址编码非法")
			@ErpDeliveryAddress.AnnoAddressId
			String addressId,
			@RegExp(regExp="^[0-9]{0,50}$",message="用户编码非法")
			@ErpDeliveryAddress.AnnoUserId
			String userId,
			//@RegExp(regExp="^[0-9]{6}$",message="省份编码为6位数字")
			@DProvince.AnnoProvinceId
			String provinceId,
			//@RegExp(regExp="^[0-9]{6}$",message="城市编码为6位数字")
			@DCity.AnnoCityId
			String cityId,
			//@RegExp(regExp="^[0-9]{6}$",message="区域编码为6位数字")
			@DRegion.AnnoRegionId
			String regionId,
			@ErpDeliveryAddress.AnnoStreet
			String street,
			@Security
			String shipName,
			@Security
			String shipZip,
			@Security
			String shipTel,
			@Mobile(message="手机号非法")
			String mobile,
			@Security
			String def,
			@ErpDeliveryAddress.AnnoMemo
			String memo,
			String flag,
			@Security
			String lng,
			@Security
			String lat){
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		ErpDeliveryAddress address1 = new ErpDeliveryAddress();
		if(StringUtils.isBlank(flag) || flag.equals("0")){
			if (StringUtils.isBlank(addressId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"地址编码不能为空");
			}
			if (StringUtils.isBlank(userId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"用户编码不能为空");
			}
			if (StringUtils.isBlank(provinceId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"省份编码不能为空");
			}
			if (StringUtils.isBlank(cityId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"城市编码不能为空");
			}
			if (StringUtils.isBlank(regionId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"地区编码不能为空");
			}
			if (StringUtils.isBlank(street)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"街道地址不能为空");
			}
			/*if (StringUtils.isBlank(shipZip)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"邮编不能为空");
			}*/
			
			if (StringUtils.isBlank(shipName)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"收货人姓名不能为空");
			}
//		if (StringUtils.isBlank(shipTel)) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"联系电话不能为空");
//		}
//		if (StringUtils.isBlank(def)) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"默认值字段不能为空");
//		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"备注不能为空");
		}
		}
		if(StringUtils.isNotBlank(flag) && flag.equals("1") ){
			
			if (StringUtils.isBlank(addressId)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"地址编码不能为空");
			}
			if (StringUtils.isBlank(flag)) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"标识不能为空");
			}
			//1：先updateuserId=,avalible=1的所有记录
			
			formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
			formMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");
			formMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
			address1.setDef("0");
			SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
					+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),
					 SqlUtis.getSQL(formMap, "a."
								+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ));
			formMap.put("erpDeliveryAddress", address1);
			this.update(formMap);
			//2:再update具体某条记录为默认
			ErpDeliveryAddress address2 = new ErpDeliveryAddress();
			address2.setDef("1");
			Map temMap = new HashMap();
			temMap.put("erpDeliveryAddress", address2);
			temMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
			SqlUtis.prepareSql(temMap, "", SqlUtis.getSQL(temMap, "a."
					+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
			this.update(temMap);
			return executeRerutn(jsonObject);
		}else{
		//1：先update记录
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		address.setAvailable("0");
		formMap.put("erpDeliveryAddress", address);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		int result = this.update(formMap);
		System.out.println(result);
		//2:再添加一条记录
		//如果编辑地址为默认地址则需要更新该用户对应的其他所有地址设置为非默认
		if(def.equals("1")){
			Map tempAddressMap = new HashMap();
			tempAddressMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
					+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpDeliveryAddress> tempList = this.list(tempAddressMap);
			if(tempList!=null){
				ErpDeliveryAddress tempAddress = new ErpDeliveryAddress();
				tempAddress.setDef("0");
				tempAddressMap.put("erpDeliveryAddress", tempAddress);
				SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempAddressMap);
			}
		}
		if(StringUtils.isNotBlank(lng)){
			address1.setLongitude(Double.parseDouble(lng));
		}
		if(StringUtils.isNotBlank(lat)){
			address1.setLatitude(Double.parseDouble(lat));
		}
		address1.setAvailable("1");
		address1.setUserId(userId);
		address1.setProvinceId(provinceId);
		address1.setCityId(cityId);
		address1.setRegionId(regionId);
		address1.setStreet(street);
		address1.setShipName(shipName);
		address1.setShipZip(shipZip);
		address1.setShipTel(shipTel);
		address1.setDef(def);
		address1.setMemo(memo);
		address1.setShipMobile(mobile);
		formMap.put("erpDeliveryAddress", address1);
		String returnId = this.insert(formMap).toString();
		System.out.println(returnId);
		if(returnId==null){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
		}
	}
	
	@Transactional
	public void updateDefault(String userId,String addressId){
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		Map formMap = new HashMap();
		formMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");
		formMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),
				 SqlUtis.getSQL(formMap, "a."
							+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ));
		address.setDef("0");
		formMap.put("erpDeliveryAddress", address);
		this.update(formMap);
		
		ErpDeliveryAddress address1 = this.erpDeliveryAddressService.one(addressId);
		address1.setDef("1");
		this.erpDeliveryAddressService.update(address1);
	}
			
}
